<template>
  <div>
      <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="auto">
        <el-row>
          <el-col :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="号码" prop="number">
              <el-input v-model="queryParams.number" type="text" placeholder="请输入号码" clearable/>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="是否被获取" prop="acquired">
              <el-select v-model="queryParams.acquired" placeholder="请选择" style="width: 200px" :clearable="true" filterable>
                  <el-option label="已被获取" :value="true"></el-option>
                  <el-option label="未被获取" :value="false"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="状态" prop="result">
              <el-select v-model="queryParams.result" placeholder="请选择" style="width: 200px" :clearable="true" filterable>
                  <el-option label="成功" value="success"></el-option>
                  <el-option label="失败" value="fail"></el-option>
                  <el-option label="未知" value="unknown"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="国家" prop="country">
              <el-select v-model="queryParams.country" placeholder="请选择" style="width: 200px" :clearable="true" filterable>
                  <el-option v-for="item in countriesList" :key="item.code" :label="item.name" :value="item.code">
                    <span class="flag-icon" :class="`flag-icon-${item.code.toLowerCase()}`"></span>
                    <span style="margin-left: 5px;">{{ item.name }}</span>
                  </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="批次" prop="groupId">
              <el-select v-model="queryParams.groupId" placeholder="请选择" style="width: 200px" :clearable="true" filterable>
                  <el-option v-for="item, index in groupList" :key="index" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6" v-if="false">
            <el-form-item label="短信状态" prop="remark">
              <el-select v-model="queryParams.acquired" placeholder="请选择" style="width: 200px" :clearable="true" filterable>
                  <el-option label="已被获取" :value="true"></el-option>
                  <el-option label="未被获取" :value="false"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :sm="12" :md="12" :lg="8" :xl="6">
            <el-form-item label="起止时间" prop="times">
              <el-date-picker
                style="width: 300px;"
                v-model="queryParams.times"
                type="datetimerange"
                range-separator="-"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="margin-bottom: 10px; display: flex; justify-content: space-between;">
        <div>
          <el-button type="success" :icon="Plus" @click="handleAddRow({})">
            新增
          </el-button>
          <el-dropdown @command="handleClickBatch($event, 'Rows', {})">
            <el-button type="primary" style="margin: 0 10px;">
              批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="export">导出</el-dropdown-item>
                <el-dropdown-item command="delete">删除</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div>
          <el-button type="success" icon="Download" @click="handleDownloadBySearch()">导出</el-button>
          <el-button type="danger" icon="Delete" @click="handleDeleteBySearch()">删除</el-button>
          <el-button type="primary" icon="search" @click="handleQuery()">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery()">重置</el-button>
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="号码" prop="number" min-width="150"></el-table-column>
        <el-table-column label="国家" prop="countryName" min-width="100">
          <template #default="{ row }">
            <span class="flag-icon" :class="`flag-icon-${row.countryCode.toLowerCase()}`"></span>
            <span style="margin-left: 5px;">{{ row.countryName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="批次" prop="groupName" min-width="100"></el-table-column>
        <el-table-column label="URL" prop="url" min-width="100" :show-overflow-tooltip="true">
          <template #default="scope">
            <span @click="copyText(scope.row.url)">{{ scope.row.url }}</span>
          </template>
        </el-table-column>
        <el-table-column label="是否被获取" prop="acquired" min-width="100">
          <template #default="scope">
            <el-tag :type="scope.row.acquired ? 'primary' : 'info'">{{ scope.row.acquired ? '是' : '否'}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="下次获取时间" prop="nextAcquireAt" min-width="160">
          <template #default="scope">
            {{ scope.row.nextAcquiredAt ? formatDate(scope.row.nextAcquiredAt) : '--'}}
          </template>
        </el-table-column>
        <!-- <el-table-column label="短信内容" prop="message" min-width="100"></el-table-column> -->
        <!-- <el-table-column label="短信状态" prop="result" min-width="100"></el-table-column> -->
        <el-table-column label="结果" prop="result" min-width="100">
          <template #default="scope">
            <el-tag type="primary" v-if="scope.row.result === 'success'">成功</el-tag>
            <el-tag type="danger" v-if="scope.row.result === 'fail'">失败</el-tag>
            <el-tag type="info" v-if="scope.row.result === 'unknown'">未知</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="导入时间" prop="createdAt" min-width="160">
          <template #default="scope">
            {{ scope.row.createdAt ? formatDate(scope.row.createdAt) : '--'}}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          v-model:current-page="paging.page"
          v-model:page-size="paging.size"
          :page-sizes="['10', '20', '30', '50', '100']"
          :size="paging.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="paging.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    <add-form ref="formRef" @refresh="handleQuery"></add-form>
    <ExportNumForm ref="exportNumFormRef" @refresh="handleQuery"></exportNumForm>
    <ConditionDel ref="conditionDelRef" @refresh="handleQuery"></ConditionDel>
  </div>
</template>


<script setup>
import {
  Plus,
  Delete,
} from "@element-plus/icons-vue";
import ConditionDel from '@/components/equipmentManagementTemplate/importNum/conditionDel.vue'
import ExportNumForm from '@/components/equipmentManagementTemplate/importNum/exportNum.vue'
import { copyText } from "@/utils";
import addForm from './form.vue';
import { getData as getGroupList } from "@/api/equipmentManagement/numberManage/grouping.api";
import { getData, delIds, apiExport } from "@/api/equipmentManagement/numberManage/importNum.api";
import useToggle from "@/hooks/useToggle";
import { formatDate } from "@/utils";
const [loading, _, setLoading] = useToggle();
import useCountries from "@/hooks/useCountries";
const { countriesList, getCountryName } = useCountries()
import { useParamStore } from '@/store'
const route = useRoute();
const { setParams, getParams, removeFalsyValues } = useParamStore()
const name = route.fullPath
onMounted(() => {
  if(!!getParams(name)) {
    queryParams.value = getParams(name)
  }
  getList()
})


const queryParams = ref({
  app: 'TG',
  method: 'mobile',
  number: void undefined,
  remark: void undefined,
  times: void undefined,
  country: void undefined,
  acquired: void undefined,
  groupId: void undefined,
  result: void undefined,
})

const paging = ref({
  size: 10,
  page: 1,
  total: 0,
});

const tableData = ref([]);

const handleSizeChange = (e) => {
  paging.value.size = e;
  getList()
};
const handleCurrentChange = (e) => {
  paging.value.page = e;
  getList()
};

const ids = ref([]);
const handleSelectionChange = (e) => {
  ids.value = e.map((item) => item.id);
}

const getList = async () => {
  try {
    setLoading(true);
    const res = await getData({
      ...queryParams.value,
      page: paging.value.page,
      size: paging.value.size,
    })
    paging.value.total = res.count;
    tableData.value = res.rows;
    setLoading(false);
  } finally {
    setLoading(false);
  }
}

const handleQuery = () => {
  paging.value.page = '1'
  paging.value.size = '10'
  setParams(queryParams.value, name)
  getList()
};

const queryFormRef = ref(null);
const handleResetQuery = () => {
  if (!queryFormRef.value) return
  queryFormRef.value.resetFields()
  handleQuery()
}

const handleClickBatch = (command, type, row) => {
  const commands = {
    export: () => handleExport(),
    delete: () => handleDelete(row),
  }[`${command}`]

  return commands && commands();
}

const conditionDelRef = ref(null);
const handleIfDelete = (row) => {
  conditionDelRef.value.init(queryParams.value, { app: queryParams.value.app, method: queryParams.value.method })
}

const exportNumFormRef = ref(null);
const handleExport = () => {
    if(ids.value.length === 0) return ElMessage.warning('请选择要导出的记录');
    const loadingDownload = ElLoading.service({
      lock: true,
      text: '正在下载中，请稍后...',
      background: 'rgba(0, 0, 0, 0.7)',
    })
    apiExport({ ids: ids.value, page: paging.value.page, size: ids.value.length, app: queryParams.value.app, method: queryParams.value.method }).then(res => {
        const decoder = new TextDecoder('utf-8');
        const buffer = new Uint8Array(res.data).buffer;
        const str = decoder.decode(buffer);
        const blob = new Blob([str], { type: 'application/octet-stream' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = res.fileName || 'default.txt';
        link.click();
        URL.revokeObjectURL(url);
    }).finally(() => {
      loadingDownload.close()
      setDialogVisible(false);
    })
}

const handleDelete = (row) => {
  if(!row.id && ids.value.length === 0) return ElMessage.warning('请选择要删除的记录');
  const tips = `确定删除${!row.id ? `${ids.value.length}条记录` : '这条记录'}?`;

  ElMessageBox.confirm(
    tips,
    '温馨提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      del()
    })


    const del = async() => {
      if(row.id) {
        const res =await delIds({ app: 'TG', ids: [Number(row.id)] })
        console.log(res);
        if(res) {
          ElMessage.success('删除成功');
          handleQuery();
        }
        return
      }

      const res =await delIds({ app: 'TG', ids: ids.value })
      if(res) {
        ElMessage.success('删除成功');
        handleQuery();
      }
    }
};

const formRef = ref(null);
const handleAddRow = (row) => {
  console.log(formRef.value);
  formRef.value.handleOpen(row)
}

const groupList = ref([]);
const getGroupListData = async() => {
  const res = await getGroupList({ app: 'TG', method: 'mobile', page: 1, size: 1000 })
  groupList.value = res.rows;
}
getGroupListData()

const handleDeleteBySearch = async () => {
  await getList()
  ElMessageBox.confirm(
        `确定删除筛选出的 ${paging.value.total} 条数据?`,
        '温馨提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            delIds({ ...queryParams.value }).then(res => {
                getList()
                if (res == 0) return ElMessage({
                    type: 'error',
                    message: '删除0条数据',
                })
                ElMessage({
                    type: 'success',
                    message: '成功删除' + res + '条数据',
                })
            }).finally(() => {
                setDialogVisible(false);
            })
        })
}

const handleDownloadBySearch = () => {
  exportNumFormRef.value.init(queryParams.value, { app: queryParams.value.app, method: queryParams.value.method })
}
</script>

<style scoped lang="scss">
.pagination {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
</style>
